package com.nmh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nmh.config.R;
import com.nmh.dto.PastureDTOS;
import com.nmh.dto.PastureDto;
import com.nmh.entity.DictType;
import com.nmh.entity.Enclosure;
import com.nmh.entity.Pasture;
import com.nmh.service.EnclosureService;
import com.nmh.service.PastureService;
import com.nmh.service.dictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
@Api(tags = "牧场模块")
@RestController
@RequestMapping("/pastures")
public class PastureController {
    @Autowired
    private PastureService pastureService;
    @Autowired
    private dictTypeService dictType;
    @Autowired
    private EnclosureService enclosureService;
    /*
    左边导航栏
     */
    @ApiOperation(value = "左边导航栏")
    @GetMapping
    public R<List<Pasture>> getall(){
        //查询所有牧场
        List<Pasture> list = pastureService.selectAll();
        return R.success(list);
    }
    @ApiOperation(value = "查询所有启用牧场")
    @GetMapping("/getByState")
    public R<List<Pasture>> getalls(){
        //查询所有启用牧场
        List<Pasture> list = pastureService.SelectAllByState();
        return R.success(list);
    }
    //自定义函数，把实体类的规范信息装配到DTO对象中方便传给前端
    public PastureDTOS transfer(Pasture pastureInfo)
    {
        PastureDTOS DtoInfo = new PastureDTOS();
        DtoInfo.setPastureId(pastureInfo.getPastureId());//牧场id
        DtoInfo.setPastureName(pastureInfo.getPastureName());//牧场名称
        DtoInfo.setStates(pastureInfo.getStates());//牧场状态
        DtoInfo.setBreed(getBreedById(pastureInfo.getLivestockId()));//牲畜类型，根据牲畜ID访问自定义函数获取
        DtoInfo.setSiteSize(pastureInfo.getSiteSize());//场地规模
        DtoInfo.setCultivationSize(pastureInfo.getCultivationSize());//养殖规模
        DtoInfo.setAddress(pastureInfo.getAddress());//地址
        DtoInfo.setLongitude(pastureInfo.getLongitude());//经度
        DtoInfo.setLatitude(pastureInfo.getLatitude());//纬度
        return DtoInfo;
    }
    //自定义函数，根据品种ID返回品种名称
    public String getBreedById(int livestock_id)
    {
        LambdaQueryWrapper<DictType> wrapper = new LambdaQueryWrapper<DictType>()
                .eq(DictType::getLivestockId,livestock_id);
        DictType dictInfo =dictType.getOne(wrapper);
        String Breed = dictInfo.getDictName();
        return Breed;
    }
    //根据牧场ID获取其所属圈舍列表
    public List<Enclosure> getCircleList(int PasId)
    {
        LambdaQueryWrapper<Enclosure> wrapper2 = new LambdaQueryWrapper<Enclosure>()
                .eq(Enclosure::getPastureId,PasId);
        Page<Enclosure> page = new Page<>(1,4);
        enclosureService.page(page,wrapper2);
        List<Enclosure> circleList = page.getRecords();
        return circleList;
    }
    //根据牧场Id去查询其所属圈舍的围栏量
    public int getInventory(int PasId)
    {
        int count =0;
        List<Enclosure> circleList = getCircleList(PasId);//自定义函数,通过牧场ID获取其所属圈舍列表
        if(circleList.size()!=0)
        {
            for(int j=0;j<circleList.size();j++)
            {
                count+=circleList.get(j).getInventory();
            }
        }
        return count;
    }
    @ApiOperation(value = "牧场查询")
    @GetMapping(value = "/queryPasture")
    //只需要牧场名称和状态的查询
    public R<Page<PastureDTOS>> queryPasture(Integer pastureId,String pastureName,Integer states)
    {
        //用模糊的分页查询，先查询出满足条件的牧场对象
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<Pasture>()
                .eq(pastureId!=null,Pasture::getPastureId,pastureId)
                .like(StringUtils.isNotEmpty(pastureName),Pasture::getPastureName,pastureName)
                .like(null!=states,Pasture::getStates,states);
        Page<Pasture>  page = new Page<>(1,10) ;
        pastureService.page(page,wrapper);

        List<Pasture> PastureList = page.getRecords();//分页对象转化为集合,方便后面取出ID获取所属圈舍信息

        List<PastureDTOS> list=new ArrayList<>();//创建一个DTO对象，对两次查询结果进行汇总

        int count = 0;//计数所属圈舍围栏量的总和

        for(int i=0;i<PastureList.size();i++)//用循环把牧场信息放入DTO对象中，并添加到DTO列表
        {
            PastureDTOS dto = transfer(PastureList.get(i));//调用自定义函数,把实体类数据封装到DTO类中
            count = getInventory(PastureList.get(i).getPastureId());//调用自定义函数，获取该牧场ID下所属圈舍的围栏量总和
            if (count!=0)
            {
                dto.setInventory(count);//存入DTO对象
            }
            list.add(dto);//加入列表
        }
        Page<PastureDTOS> pageInfo=new Page<>(1,4);
        pageInfo.setRecords(list);//集合对象放入分页对象中,传给前端
        return R.success(pageInfo);
    }
    @ApiOperation(value = "状态修改")
    @PostMapping(value = "/changeStates")
    public R StopPasture(int PastureId) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<Pasture>()
                .eq(Pasture::getPastureId, PastureId);
        Pasture pastureInfo = pastureService.getOne(wrapper);
        if (pastureInfo.getStates() == 0)//如果状态码是0，表示要由启用状态改为停用状态
        {
            if (getInventory(PastureId) == 0) {
                pastureInfo.setStates(1);
                if (pastureService.updateById(pastureInfo))
                {
                    Pasture newInfo = pastureService.getOne(wrapper);

                    return R.success(newInfo);
                }
            }
//            return R.error("停用失败，有未出栏的牲畜", pastureInfo);
            return R.error("停用失败，有未出栏的牲畜","401");
        }
        else {
            pastureInfo.setStates(0);//由停用改为启用状态
            if (pastureService.updateById(pastureInfo)) {
                Pasture newInfo = pastureService.getOne(wrapper);
                return R.success(newInfo);
            }
        }
//        return R.Failed("修改失败,状态有误",pastureInfo);
        return R.error("修改失败","401");
    }

    @ApiOperation(value = "删除牧场")
    @DeleteMapping(value = "/deletePasture")
    public R deletePasture(int pastureId) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<Pasture>()
                .eq(Pasture::getPastureId,pastureId);
        Pasture pasInfo = pastureService.getOne(wrapper);
        if(pasInfo!=null)//判断要删除的牧场是否存在
        {
            if(pasInfo.getStates()==1)//处于停用状态的牧场才能删除
            {
                if(pastureService.removeById(pastureId))
                {
                    return R.success("删除成功");
                }
                return R.error("删除失败，请检查牧场信息","401");
            }
            return R.error("删除失败，请先将牧场停用","401");
        }
        return R.error("删除失败，此牧场信息不存在","401");
    }

    @ApiOperation(value = "牧场详情")
    @GetMapping(value = "/PastrueDetail")
    public R PastrueDetail(int pastureId) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<Pasture>()
                .eq(Pasture::getPastureId,pastureId);
        Pasture pasInfo =  pastureService.getOne(wrapper);//先查出牧场对象
        // 调用自定义函数把牧场详细情况赋给DTO对象
        PastureDTOS DtoInfo = transfer(pasInfo);
        if(pasInfo!=null){
            List<Enclosure> circleList = getCircleList(pastureId);//自定义函数,通过牧场ID获取其所属圈舍列表
            for(int i=0;i<circleList.size();i++)
            {
                DtoInfo.setCircleList(circleList);//把所属圈舍列表添加进VO对象
            }
            return R.success(DtoInfo);
        }
        return R.error("牧场信息不h存在","401");
    }
    @ApiOperation(value = "新增牧场")
    @PostMapping("/insertPasture")
    public R<String> insertPasture(@RequestBody  PastureDto pastureDto) {
        boolean res = pastureService.searchPasture(pastureDto.getPastureName());
        if (res) {
            boolean rows = pastureService.insertPasture(pastureDto);
            Pasture pasture=pastureService.searchPastureByName(pastureDto.getPastureName());
            return rows ? R.success("新增成功") : R.error("新增失败","100401" );
        }
        return R.error("该牧场已存在","100401" );
    }
    @ApiOperation(value = "修改牧场")
    @PutMapping("/updatePasture")
    public R updatePasture(@RequestBody  PastureDto pastureDto) {
        boolean res = pastureService.searchPasture(pastureDto.getPastureName());
        String name=pastureService.searchPastureById(pastureDto.getPastureId());
        if (res||pastureDto.getPastureName().equals(name)) {
            System.out.println(pastureDto.getPastureId());
            boolean rows = pastureService.updatePasture(pastureDto);
            Pasture pasture=pastureService.searchPastureByName(pastureDto.getPastureName());
            return rows ? R.success(pasture) : R.error("修改失败/存在值为空的情况", "100401");
        }
        return R.error("该牧场名已存在", "100401");
    }
}
